//
//  SEGBasicWKWebViewCookieManager.m
//  SEGWebView
//
//  Created by 山刘 on 2021/1/21.
//

#import "SEGBasicWKWebViewCookieManager.h"
#import "SEGHTTPManager.h"

@implementation SEGBasicWKWebViewCookieManager

/**
 同步cookie，请求网页
 
 @author Sam
 */
+(void)syncCookieThenLoadWeb:(WKWebView*)webView url:(NSURL*)url {
    if (!url || !webView) return;
    
    @try {
        if (@available(iOS 11.0, *)){
                        
            NSArray <NSHTTPCookie *>* cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies;
            
            
            NSDictionary<NSString *, NSString *> *cookieDict = [self getGlobalCookies];
            NSArray *cookieKeys = [cookieDict allKeys];
            //NSArray *cookieValues = [cookieDict allValues];
            
            dispatch_group_t g = dispatch_group_create();
            dispatch_queue_t q = dispatch_queue_create("sync.cookie.wkweb.queue", DISPATCH_QUEUE_CONCURRENT);
            
            //NSMutableArray<NSString*> *cookiesSyncTempt = [NSMutableArray array];
            
            for (NSHTTPCookie *cookie in cookieJar) {
                
                //if ([cookiesSyncTempt containsObject:cookie.name]) continue;
                if (!([cookieKeys containsObject:cookie.name] /*&& [cookieValues containsObject:cookie.value]*/)) continue;
                if ([cookie.name isEqualToString:@"JSESSIONID"]) continue;
                
                //[cookiesSyncTempt addObject:cookie.name];
                
                NSLog(@"🍪🍪🍪 开始同步的有效cookie： %@===%@",cookie.name,[@(cookie.sessionOnly) stringValue]);
            
                dispatch_group_async(g, q, ^{
                    
                    dispatch_semaphore_t s = dispatch_semaphore_create(0);
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [[WKWebsiteDataStore defaultDataStore].httpCookieStore setCookie:cookie completionHandler:^{
                            
                            NSLog(@"🍪🍪🍪 同步完成： %@：%@",cookie.name,cookie.value);
                    
                            dispatch_semaphore_signal(s);
                            
                        }];
                        
                    });
                    
                    dispatch_semaphore_wait(s, dispatch_walltime(NULL, 500* NSEC_PER_MSEC));
                    
                });
            }
            
            dispatch_group_notify(g, dispatch_get_main_queue(), ^{
                
                [self loadWeb:webView url:url];
                
            });
            
        } else {
            [self loadWeb:webView url:url];
            
        }
        
    } @catch (NSException *exception) {
        NSLog(@"🍪🍪🍪 报错： %@",exception.name);
    }
}

/**
 请求网页
 
 @author Sam
 */
+(void)loadWeb:(WKWebView*)webView url:(NSURL*)url {
    
    NSMutableURLRequest *requestM = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:120];
    [requestM setHTTPShouldHandleCookies:YES];
    
    NSDictionary<NSString *, NSString *> *cookieDict = @{@"Cookie": [self getCookiesString]};
    requestM.allHTTPHeaderFields = cookieDict;

    [webView loadRequest:requestM];
    
    NSLog(@"🔗🔗🔗 请求URL： %@",url.absoluteString);
}

/**
 获取全局cookie
 
 */
+(NSDictionary<NSString *, NSString *>*)getGlobalCookies {
    NSDictionary<NSString *, NSString *> *cookieDict = [[NSUserDefaults standardUserDefaults] objectForKey:kSEGUsualCookie];
    if (!cookieDict) {
        cookieDict = [NSDictionary dictionary];
    }
    return cookieDict;
}

+ (NSString *)getCookiesString {
    
    __block NSString *_cookieStr = @"";
    NSDictionary<NSString *, NSString *> *cookieDict = [self getGlobalCookies];
    [cookieDict enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL * _Nonnull stop) {
        NSString *str = [NSString stringWithFormat:@"%@=%@; ", name, value];
        _cookieStr = [_cookieStr stringByAppendingString:str];
    }];
    return _cookieStr;
}

@end
